package liurong.driver.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 计数信号量。设置最大量，acquire()和release()最大执行量为计数信号量
 * 
 * @author liurong
 *
 */
public class SemaphoneTest1 {
	public static void main(String[] args) throws Exception {
		ExecutorService executorService = Executors.newCachedThreadPool();
//		ExecutorService executorService = new ThreadPoolExecutor(2, 2, 60L, TimeUnit.SECONDS,
//				new LinkedBlockingQueue<>(5));
		final Semaphore semaphore = new Semaphore(2);
		for (int i = 0; i < 10; i++) {
			final int index = i;
			semaphore.acquire();
			Runnable runnable = new Runnable() {
				public void run() {
					try {
						System.out.println(index);
						TimeUnit.SECONDS.sleep(3);
						semaphore.release();
					} catch (InterruptedException e) {
					}
				}
			};
			executorService.execute(runnable);
		}

		executorService.shutdown();
	}
}
